import React from 'react';
import style from './index.less';
import { Form, Input, Table, Popconfirm, Button } from 'antd';
import { useSetState, useUpdateEffect, useMount } from 'ahooks';
import _ from 'lodash';
import { DndProvider } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';

import { TRDefault, TRMessage } from '@/components';
import { default as TRIconModal } from '../../../ChangeIconModal'; // 更换图标
import { default as DragableBodyRow } from '../../../DragableBodyRow';
import {
  createFromIconfontCN,
  FormOutlined,
  DeleteOutlined,
  SwapOutlined,
  CloseCircleOutlined,
  SaveOutlined,
} from '@/utils/antdIcons';
import { tableLocale } from '#/components/PageEmpty';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1635810_mwd5ah7yf.js',
});
const FormItem = Form.Item;

const AMenuCompontent = ({ form, firstMenuListModel, echoApp, defaultFlag }) => {
  const operation_Type = {
    add: 1,
    edit: 2,
    delete: 3,
  };
  const [state, setState] = useSetState({
    dataList: [],
    dataSource: [],
    menuNanme: '',
    menuNanmeDisabled: true,
  });

  const components = { body: { row: DragableBodyRow } };
  const moveRow = (dragIndex, hoverIndex) => {
    const { dataSource, dataList } = state;
    const dragRow = dataSource[dragIndex];
    const dataSwper = update(dataSource, {
      $splice: [
        [dragIndex, 1],
        [hoverIndex, 0, dragRow],
      ],
    });
    const dataRemove = _.reduce(
      dataList,
      (t, v) => {
        if (v.operationType === 3) return [...t, v];
        return t;
      },
      [],
    );
    const newSortArr = [...dataSwper, ...dataRemove];
    setState({
      dataList: newSortArr,
    });
  };

  useMount(() => {
    setState({
      dataList: firstMenuListModel,
    });
  });

  useUpdateEffect(() => {
    const dataSource = _.reduce(
      state.dataList,
      (t, v) => {
        if (v?.operationType !== operation_Type['delete']) {
          return [...t, v];
        } else {
          return t;
        }
      },
      [],
    );
    setState({ dataSource });
    echoApp && echoApp(state.dataList);
  }, [state.dataList]);

  // 修改icon
  const handleChangeIcon = async (firstMenuId, type) => {
    const iconModel = await TRIconModal.show(firstMenuId, type);
    const _updataData = _.map(state.dataList, (_v) => {
      if (_v.firstMenuId === iconModel.firstMenuId) {
        _v.icon = iconModel.icon;
      }
      return _v;
    });
    setState({
      dataList: _updataData,
    });
  };

  // 添加一级菜单
  const _add = async () => {
    const _isExist = state.dataList.some((_v) => {
      return _v.operationType !== operation_Type['delete'] && _v.name === state.menuNanme.trim();
    });
    if (_isExist) {
      TRMessage.error(`${state.menuNanme}已存在，请重新填写`);
    } else {
      const newMenu = {
        firstMenuId: _.uniqueId('addMenu-'),
        name: state.menuNanme.trim(),
        icon: 'icongongfang',
        sort: state.dataSource?.length || 0,
        secondMenuList: [],
        operationType: operation_Type['add'], // 操作类型-1新增-2修改-3删除
      };
      setState({
        dataList: [...state.dataList, newMenu],
        menuNanme: '',
      });
    }
  };

  useUpdateEffect(() => {
    const name = (state?.menuNanme || '').trim();
    setState({
      menuNanmeDisabled: defaultFlag || !name,
    });
  }, [state.menuNanme, defaultFlag]);

  // 添加一级菜单名称
  const _onChange = (e) => {
    const { value = '' } = e.target;
    setState({
      menuNanme: value,
    });
  };

  // 删除一级菜单
  const _confirmDelte = (id) => {
    const _filterArr = _.reduce(
      state.dataList,
      (t, v) => {
        if (v.firstMenuId === id && v.firstMenuId.includes('addMenu-')) {
          return t;
        } else if (v.firstMenuId === id && !v.firstMenuId.includes('addMenu-')) {
          v.operationType = operation_Type['delete'];
          v.sort = -1;
          return [...t, v];
        } else {
          return [...t, v];
        }
      },
      [],
    );
    setState({
      dataList: _filterArr,
    });
  };

  const handleEdit = (id, type) => {
    const firstMenu = state.dataList.find((item) => item.firstMenuId === id);
    switch (type) {
      case 'edit':
        firstMenu.alternativeName = firstMenu.name;
        break;
      case 'save':
        if (!firstMenu.alternativeName.trim()) return TRMessage.error('一级菜单不能为空！');
        const _isExist = _.find(state.dataList, (_v) => {
          return (
            _v.operationType !== operation_Type['delete'] &&
            _v.firstMenuId !== id &&
            firstMenu.alternativeName.trim() === _v.name
          );
        });
        if (_isExist) return TRMessage.error(`${firstMenu.alternativeName}已存在，请重新填写`);
        firstMenu.name = firstMenu.alternativeName.trim();
        break;
      case 'cancel':
        firstMenu.alternativeName = firstMenu.name;
        break;
    }
    firstMenu.isEdit = !firstMenu.isEdit;
    const data = _.map(state.dataList, (v) => {
      if (v.firstMenuId === id) return firstMenu;
      return v;
    });
    setState({
      dataList: data,
    });
  };

  const handleChange = (e, id) => {
    const { value = '' } = e.target;
    const _data = _.map(state.dataList, (_v) => {
      if (_v.firstMenuId === id) {
        _v.alternativeName = value;
      }
      return _v;
    });
    setState({
      dataList: _data,
    });
  };

  const columns = [
    {
      dataIndex: 'name',
      key: 'name',
      render: (_, record) => (
        <div className="appIcon">
          <MyIcon style={{ fontSize: 14, marginRight: 0 }} type={record.icon} />
          {record.isEdit ? (
            <Input
              value={record.alternativeName}
              maxLength={10}
              style={{ width: '150px' }}
              onChange={(e) => handleChange(e, record.firstMenuId)}
            />
          ) : (
            <span className={style.appName}>{record.name}</span>
          )}
        </div>
      ),
    },
    {
      dataIndex: 'icon',
      key: 'icon',
      align: 'right',
      render: (_, record) => (
        <div className="appEdit">
          {defaultFlag ? null : (
            <React.Fragment>
              <a
                className={style.recordRight}
                onClick={() => handleChangeIcon(record.firstMenuId, 'edit')}
              >
                更换图标
              </a>
              {record.isEdit ? (
                <React.Fragment>
                  <SaveOutlined
                    style={{ color: 'var(--font-primary)' }}
                    onClick={() => handleEdit(record.firstMenuId, 'save')}
                  />
                  <CloseCircleOutlined
                    className={style.recordRight}
                    onClick={() => handleEdit(record.firstMenuId, 'cancel')}
                  />
                </React.Fragment>
              ) : (
                <FormOutlined
                  className={style.recordRight}
                  onClick={() => handleEdit(record.firstMenuId, 'edit')}
                />
              )}
              <Popconfirm
                title="确认删除？"
                onConfirm={() => _confirmDelte(record.firstMenuId)}
                onCancel={() => {}}
                okText="是"
                cancelText="否"
              >
                <DeleteOutlined className={style.recordRight} />
              </Popconfirm>
              <SwapOutlined rotate={90} />
            </React.Fragment>
          )}
        </div>
      ),
    },
  ];

  return (
    <div>
      <Form form={form} layout="inline" style={{ marginBottom: '20px' }}>
        <FormItem>
          <Input
            maxLength={10}
            value={state.menuNanme}
            onChange={_onChange}
            placeholder="请输入菜单名称"
            disabled={defaultFlag}
            rules={[
              {
                required: false,
                message: '请输入菜单名称',
              },
            ]}
          />
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={_add} disabled={state.menuNanmeDisabled}>
            添加
          </Button>
        </FormItem>
      </Form>

      {state.dataSource?.length ? (
        <React.Fragment>
          {defaultFlag ? (
            <Table
              locale={tableLocale}
              className={style.aMenuTableName}
              showHeader={false}
              pagination={false}
              columns={columns}
              rowKey="firstMenuId"
              dataSource={state.dataSource}
              scroll={{
                y: 390,
              }}
            />
          ) : (
            <DndProvider backend={HTML5Backend}>
              <Table
                locale={tableLocale}
                className={style.aMenuTableName}
                showHeader={false}
                pagination={false}
                columns={columns}
                rowKey="firstMenuId"
                dataSource={state.dataSource}
                components={components}
                onRow={(_, index) => ({
                  index,
                  moveRow,
                })}
                scroll={{
                  y: 390,
                }}
              />
            </DndProvider>
          )}
        </React.Fragment>
      ) : (
        <TRDefault type="emptysm" />
      )}
    </div>
  );
};

export default AMenuCompontent;
